<template>
  <div
    class='channels-container'
    ref="article-list"
  >
    <van-pull-refresh
      v-model="isPullLoading"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="isFinished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <channel-items
          v-for="(channels, index) in channelsList"
          :key="index"
          :channels="channels"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getChannelsList } from '@/api/user'
import channelItems from '@/components/channel-item/channel-items'
import { Toast } from 'vant'

export default {
  name: 'channelList',
  components: {
    channelItems
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      channelsList: [],
      loading: false, // 数据加载状态
      isFinished: false,
      isTimestamp: null, // 时间戳
      isPullLoading: false, // 下拉刷新加载状态
      timer: null, // 定时器，解决退出阅读后，滚动条移位
      articleListScroll: 0 // 滚动条的位置
    }
  },
  mounted () {
    // 解决退出文章阅读后，滚动条移位的问题；获取滚动位置，退出阅读后，手动赋值滚动条的位置
    const articleList = this.$refs['article-list']
    articleList.onscroll = () => {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.articleListScroll = articleList.scrollTop
      }, 50)
    }
  },
  activated () {
    this.$refs['article-list'].scrollTop = this.articleListScroll
  },
  methods: {
    async onLoad () {
      // 1、请求获取数据
      const { data } = await getChannelsList({
        channel_id: this.channel.id, // 频道的 ID
        timestamp: this.isTimestamp || Date.now()// 时间戳。请求新的推荐数据传当前的时间戳，请求历史的推荐数据传指定的时间戳，请求下一页使用上一次返回的时间戳
      })
      // 2、把数据放在 list 数组中
      const { results } = data.data
      this.channelsList.push(...results)
      // 3、设置本次加载状态结束，他才可以判断是否需要加载下一次，否则就永远停在加载状态
      this.loading = false
      // 4、数据全部加载完成
      // 如果 results.length 为 true，证明后面还有数据
      if (results.length) {
        // 更新获取下一页数据的页面
        this.isTimestamp = data.data.pre_timestamp
      } else {
        // 没有数据了，将加载状态设置为 true 表示结束加载，不再触发加载更多
        this.isFinished = true
      }
    },
    async onRefresh () {
      const { data } = await getChannelsList({
        channel_id: this.channel.id,
        timestamp: Date.now()
      })
      const { results } = data.data
      this.channelsList.unshift(...results)
      this.isPullLoading = false
      Toast({
        message: '更新成功',
        duration: 700
      })
    }
  }
}
</script>
<style lang='less' scoped>
.channels-container {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 50px;
  top: 90px;
  overflow-y: auto;
}
</style>
